import api from '@/api/index'

const flag = {}
const wait = {}
export const getCode = (code) => {
  return new Promise((resolve) => {
    const temp = sessionStorage[code]
    if (temp) {
      resolve(JSON.parse(temp))
    } else {
      if (flag[code]) {
        wait[code].push(() => {
          resolve(getCode(code))
        })
      } else {
        flag[code] = true
        wait[code] = []
        api
          .codeList({
            parentCode: code,
            pageInfo: {
              pageNum: 1,
              pageSize: 999
            }
          })
          .then(({ data }) => {
            const arr = data.map((item) => {
              return {
                itemName: item.itemName,
                itemValue: item.itemValue,
                itemColor: item.itemColor
              }
            })
            // localStorage
            sessionStorage[code] = JSON.stringify(arr)
            wait[code].forEach((cb) => {
              cb()
            })
            flag[code] = false
            resolve(arr)
          })
      }
    }
  })
}

export const getCodeValue = async (/**值集代码 */ code, /**值集id */ id) => {
  if (!id) return ''
  const arr = await getCode(code)
  const val = arr.find((item) => item.itemValue === id)
  return val ? val.itemName : ''
}
export const getCodeValueAndColor = async (/**值集代码 */ code, /**值集id */ id) => {
  if (!id)
    return {
      itemName: '',
      itemColor: '#000000'
    }
  const arr = await getCode(code)
  const val = arr.find((item) => item.itemValue === id)
  return val
    ? {
        itemName: val.itemName,
        itemColor: val.itemColor || '#000000'
      }
    : {
        itemName: '',
        itemColor: '#000000'
      }
}
